/**
 * Created by pjn on 2017/5/2.
 */

var fullFlag = false;
var height = 0;
var width = 0;
var start = 0;
var length = 10;

var loadNotice = function (type, search) {
    if (type == 0)
        start += length;
    else if (type == 1)
        start -= length;
    else if (type == 2) {
        start = 0;
        $("#noticeList").html("");
    }

    if (!search)
        search = "";
    $.ajax({
        url: "../rds_noticelist/getNoticeList4DT",
        type: "POST",
        data: {
            start: start,
            length: length,
            userId: gUserLoginResult.userId,
            search: search
        },
        success: function (msg) {
            if (msg) {
                if (msg.isSuccess) {
                    var dataList = msg.jsonData;
                    for (var i in dataList) {
                        var data = dataList[i], content = data.noticeContent, text = $(content).text().substring(0, 23);
                        if ($(content).find("img[src]").length != 0) {
                            var src = $(content).find("img[src]")[0].src;
                            if (src.substring(src.length - 4) == "html")
                                src = null;
                        }
                        var img = '<img src="' + src + '" >';
                        if (!src)
                            img = '<img src="../images/no-pic.png" >';
                        var html = '<div class="notice_block">\n' +
                            '<label>\n' +
                            '    <div class="notice_content">\n' +
                            '        <div class="notice_head">\n' +
                            '            <input type="checkbox" value="' + data.userNoticeId + '" ></input>\n' +
                            '            <h4>' + data.noticeTitle + '</h4>\n' +
                            '            <h5>' + data.noticeSendTime + '</h5>\n' +
                            '        </div>\n' +
                            '        <div class="notice_body">\n' + img +
                            '        </div>\n' +
                            '        <div class="notice_foot">\n' +
                            '        <h5>' + text + '...</h5>\n' +
                            '            <h4 style="margin-top: 30px;">查看内容</h4>\n' +
                            '        </div>\n' +
                            '    </div>\n' +
                            '    <a id="' + data.userNoticeId + 'Notice" class="request_btn notice_close"></a>\n' +
                            '<label>\n' +
                            '</div>';
                        $("#noticeList").append(html);
                        $('#' + data.userNoticeId + 'Notice').data("jsonData", data);
                    }
                }
            }
        }
    })
};
$(function () {
    $('#toolBtn').data("isDelete", true);
    loadNotice();
// 通知公告modal
    $(document).on("click", ".notice_block a", function () {
        $.showNotice($(this).data("jsonData"))

    });
    var request = _debounce(function () {
        start += length;
        loadNotice();
    }, 1000);
    $(window).scroll(function () {
        var sub = $(document).scrollTop() + $(window).height() - $(document).height();
        if (Math.abs(sub) < 1) {
            // console.log(1111);
            request();
        }
    })

    $("#searchBtn").click(function () {
        console.log($("#searchValue").val());
        loadNotice(2, $("#searchValue").val());
    });

    $("#toolBtn").click(function () {
        var $checked = $(".notice_head input:checked");
        for (var i = 0; i < $checked.length; i++)
            $checked[i].checked = false;
        $('#toolBtn').data("isDelete", !$('#toolBtn').data("isDelete"));
        var type = $('#toolBtn').data("isDelete");
        if (!type) {
            $(".notice_head input").show();
            $("#deleteBtn").show();
            $("a[id$='Notice']").hide();
        } else {
            $(".notice_head input").hide();
            $("#deleteBtn").hide();
            $("a[id$='Notice']").show();
        }
    })

    $(".moreBtn").click(function () {
        loadNotice(0)
    });

    $("#deleteBtn").click(function () {
        var $checked = $(".notice_head input:checked"), checkList = [];
        for (var i = 0; i < $checked.length; i++) {
            checkList.push($checked[i].value);
        }
        if (i != 0) {
            bootbox.confirm({
                buttons: {
                    confirm: {
                        label: '<i class="fa fa-check"></i> 确定',
                        className: 'btn btn-primary btn-flat'
                    },
                    cancel: {
                        label: '<i class="fa fa-close"></i> 取消',
                        className: 'btn btn-warning btn-flat pull-left'
                    }
                },
                message: '<i class="fa fa-question-circle-o"></i> <b class="customer-title">确定删除该' + i + '条数据吗?</b>',
                callback: function (result) {
                    if (result) {
                        $.ajax({
                            url: '../rds_noticelist/deleteNoticeByUserNoticeId',
                            type: 'post',
                            dataType: 'json',
                            data: {
                                userNoticeIds: checkList.join(",")
                            },
                            success: function (msg) {
                                if (msg) {
                                    if (msg.isSuccess == true) {
                                        $.alert("数据删除成功", 1);
                                        $("#toolBtn").click()

                                        loadNotice(2)
                                    } else {
                                        $.alert("数据删除失败", 2);
                                    }
                                } else {
                                    $.alert('系统错误，请联系管理员', 2);
                                }
                            },
                            error: function () {
                                $.alert('系统错误，请联系管理员', 2);
                            }
                        });
                    }
                }
            });
        } else $.alert("请选择要删除的数据", 2)
    })
    /*gMainDT = $("#mainDataTables").DataTable({

        columns: [{
            data: "userNoticeId",
            render: function (data, type, row, meta) {
                var checkId = "checkbox" + (parseInt(meta.row) + 1);
                return "<input type='checkbox' value='" + data + "' id='" + checkId + "'>";
            }
        }, {
            data: "userNoticeId",
            targets: 0
        }, {
            data: "noticeTitle",
            render: function (data, type, row) {
                return "<p style='cursor: pointer' onclick='$.showNotice(" + JSON.stringify(row) + ")' >" + data + "</p>"
            }
        }, {
            data: "noticeSendTime",
            render: function (data, type, row, meta) {
                return data.substring(0, 10);
            }
        }, {
            data: "isRead",
            render: function (data, type, row) {
                return data == 0 ? "未读" : "已读";
            }
        }, {
            data: "userNoticeId",
            render: function (data, type, row) {
                // 左侧工具栏按钮的权限
                // var buttonInsert = "<button class='btn btn-primary btn-xs btn-flat' onclick='$.addNotice()' title='添加'><i class='fa fa-plus-square'></i></button>";
                var buttonDelete = "<button class='btn btn-primary btn-xs btn-flat' onclick='$.deleteSelectNotice(" + JSON.stringify(row) + ")' title='删除'><i class='fa fa-minus-square'></i></button>";
                var buttonSelect = "<button class='btn btn-primary btn-xs btn-flat' onclick='$.showNotice(" + JSON.stringify(row) + ")' title='详情'><i class='glyphicon glyphicon-eye-open'></i></button>";
                var buttonOperation = "";
                //gInsert == 0 ? buttonOperation : buttonOperation += buttonInsert + " ";
                gSelect == 0 ? buttonOperation : buttonOperation += buttonSelect + " ";
                gDelete == 0 ? buttonOperation : buttonOperation += buttonDelete;
                buttonOperation == "" ? buttonOperation = "无权限" : buttonOperation;
                return buttonOperation;
            }
        }],
        dom: "<'row'<'col-md-4'l><'#mainToolbar.col-md-8'>r>t<'row'<'col-md-6'i><'col-md-6'p>>",
        initComplete: function () {
            // 下拉工具栏按钮的权限
            $("#mainToolbar").empty();
            var strToolBar = "<div class='pull-right'><div class='btn-group'><button type='button' class='btn btn-primary btn-sm btn-flat'><i class='fa fa-cog'></i> 操作</button>";
            strToolBar += "<button type='button' class='btn btn-primary btn-sm btn-flat dropdown-toggle' data-toggle='dropdown' aria-haspopup='true' aria-expanded='false'>";
            strToolBar += "<span class='caret'></span><span class='sr-only'>切换下拉</span></button><ul class='dropdown-menu'>";
            strToolBar += "<li><button href='#' class='btn btn-primary btn-sm btn-flat btn-block' onclick='gMainDT.ajax.reload(null, false);'><i class='fa fa-refresh'></i> 刷新</button></li>";
            // 下拉工具栏不处理更新事件，但今后可能需要审核等功能，替换该位置即可
            //var buttonUpdate = "<li><button href='#' class='btn btn-warning btn-sm btn-flat btn-block' onclick='$.updateOrg()'><i class='fa fa-edit'></i> 编辑</button></li>";
            var buttonDelete = "<li><button href='#' class='btn btn-primary btn-sm btn-flat btn-block' onclick='$.deleteSelectNotice(0)'><i class='fa fa-minus-square'></i> 删除</button></li>";
            //var buttonInsert = "<li><button href='#' class='btn btn-primary btn-sm btn-flat btn-block' onclick='$.addNotice()'><i class='fa fa-plus-square'></i> 添加</button></li>";
            //gInsert == 0 ? strToolBar : strToolBar += buttonInsert;
            gDelete == 0 ? strToolBar : strToolBar += buttonDelete;
            // 同上方更新事件同时处理
            //gUpdate == 0 ? strToolBar : strToolBar += buttonUpdate;
            //  strToolBar += buttonDelete;
            strToolBar += "</ul></div> " +
                "<div class='input-group input-group-sm'><input type='text' class='form-control' name='searchText' placeholder='标题'>";
            strToolBar += "<span class='input-group-btn'><button class='btn btn-primary btn-flat' type='button' onclick='$(this).searchDT()'><i class='fa fa-search'></i></button></span></div></div>";
            $("#mainToolbar").append(strToolBar);
        },
        processing: true,
        serverSide: true,
        ordering: false,
        select: true,
        autoFill: true,
        displayLength: 20,
        lengthMenu: [[5, 10, 15, 20, 50, 100, 150, -1], [5, 10, 15, 20, 50, 100, 150, "All"]],
        language: {
            url: "zh_cn.json"
        },
        fnDrawCallback: function () {// 序号自增回调函数
            var api = this.api();
            var startIndex = api.context[0]._iDisplayStart;
            api.column(1).nodes().each(function (cell, i) {
                cell.innerHTML = startIndex + i + 1;
            });
        }
    });*/
});


$.showNotice = function (data) {
    $("#showNoticeTitle").text(data.noticeTitle);
    $("#showNoticeTime").text(data.noticeSendTime.substring(0, 10));
    $("#showSendName").text(gUserLoginResult.userName);
    $("#showNoticeContent").html(data.noticeContent);
    $("#showInfoModal").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    });
    $.updateIsRead(data.userNoticeId)
};

$.closeShowModal = function () {
    $("#showInfoModal").modal("hide");
    $('#body').prop('scrollTop', '0');
    fullFlag = true;
    $.fullShowModal();
};

//更新已读状态
$.updateIsRead = function (userNoticeId) {
    $.ajax({
        url: "../rds_noticelist/updateIsRead",
        type: "post",
        dataType: "json",
        data: {
            userNoticeId: userNoticeId
        },
        success: function (msg) {
        },
        error: function (msg) {
            $.alert("系统错误！", 4);
        }
    });
};

$.fullShowModal = function () {
    if (fullFlag == false) {
        fullFlag = true;
        height = $(document).height() - $("#header").height() - $("#footer").height() - 60;
        width = $(document).width();
        height *= 0.8;
        width *= 0.8;
        $("#dialog").css("top", 0);
        $("#dialog").css("left", -width * 0.2);
    } else {
        fullFlag = false;
        height = 400;
        width = 600;
        $("#dialog").css("top", 0);
        $("#dialog").css("left", 0);
    }
    $("#content").css("width", width);
    $("#body").css("width", width + 10);
    $("#body").css("height", height);
    $("#body").css("max-height", height);
};